<template>
  <div id="app">
    <el-button @click="handleClick" :loading="loading" type="primary"
      >提交</el-button
    >
  </div>
</template>

<script>
// 可复用的异常处理
function handleConfirmFlow(fn) {
  return async function (...args) {
    try {
      await this.$confirm("确认提交吗？");
      await fn.call(this, ...args);
      this.$message({
        type: "success",
        message: "提交成功"
      });
    } catch (error) {
      // 统一对错误进行拦截
      if (error === "cancel") {
        this.$message({
          type: "info",
          message: "提交已取消"
        });
      } else {
        this.$message({
          type: "error",
          message: error.message || "提交失败"
        });
      }
    }
  };
}

// 模拟接口请求
const api = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve();
      // reject(new Error("提交失败"));
    }, 1000);
  });
};
export default {
  data() {
    return {
      loading: false
    };
  },
  methods: {
    handleClick: handleConfirmFlow(async () => {
      const res = await api();
      // res
      console.log(res);
    })
  }
};
</script>

<style></style>
